const baseURL = "https://api-hmugo-web.itheima.net/api/public/v1"
let axiosCount = 0;
export const axios = (params) => {
    //手写请求拦截器
    if (params.url.indexOf('/my/') > -1) {
        const token = wx.getStorageSync('token');
        if (!token) {
            //没有token的情况，跳转到授权页面
            wx.navigateTo({
                url: '/pages/auth/index'
            });
        } else {
            //有token
            params.header = { Authorization: token };
        }

    }
    //显示loading
    // wx.showLoading({
    //     title: '疯狂加载中',
    //     mask: true,
    // });
    wx.showNavigationBarLoading();
    axiosCount++;

    return new Promise((resolve, reject) => {
        wx.request({
            ...params,
            url: baseURL + params.url,
            success: (result) => {
                //    成功回调函数
                resolve(result.data.message)
            },
            fail: (error) => {
                //    失败回调函数
                wx.wx.showToast({
                    title: '数据获取失败，请重试',
                    icon: 'none',
                    //提示停留的时间
                    duration: 200
                });

            },
            complete: () => {
                axiosCount--;
                if (axiosCount == 0) {
                    // 隐藏loading
                    // wx.hideLoading();
                    wx.hideNavigationBarLoading();
                }
            }
        });

    })

    // 封装axios.get axios.post
    // 简写
    axios.get = (url, data = {}) => {
        let params = { url, data };
        return axios(params);
    }
    // post请求
    axios.post = (url, data = {}) => {
        let params = { url, data, method: "POST" };
        return axios(params);
    }

}